package com.yaorange.web.controller.common;

import java.time.LocalDate;
import java.util.concurrent.ThreadLocalRandom;
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;

import com.yaorange.common.annotation.Anonymous;
import com.yaorange.common.core.controller.BaseController;
import com.yaorange.common.core.domain.AjaxResult;
import com.yaorange.common.core.redis.RedisCache;
import com.yaorange.common.constant.CacheConstants;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 短信验证码Controller
 *
 * @author ruoyi
 */
@Tag(name = "短信验证码管理")
@RestController
@RequestMapping("/common/sms")
public class SmsController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(SmsController.class);

    @Autowired
    private RedisCache redisCache;

    /**
     * 发送短信验证码
     *
     * @param mobilePhone 手机号
     * @return
     */
    @Operation(summary = "发送短信验证码")
    @Parameter(name = "mobilePhone", description = "手机号", required = true, schema = @Schema(type = "string"))
    @GetMapping("/sendValidateCode")
    @Anonymous
    public AjaxResult sendValidateCode(@RequestParam("mobilePhone") String mobilePhone) {
        // 正则表达式校验手机号格式
        if (!Pattern.compile("^1[3-9]\\d{9}$").matcher(mobilePhone).matches()) {
            return AjaxResult.error("手机号格式不正确");
        }

        // 在发送前添加检查
        String dailyCounterKey = CacheConstants.SMS_COUNTER_PREFIX + mobilePhone +
                ":" + LocalDate.now();
        Long count = redisCache.increment(dailyCounterKey);
        if (count == 1) {
            // 首次设置时添加24小时过期
            redisCache.expire(dailyCounterKey, 24, TimeUnit.HOURS);
        }
        if (count > 10) {
            return AjaxResult.error("今日发送次数已达上限");
        }

        // 生成6位随机验证码
        String code = String.valueOf(ThreadLocalRandom.current().nextInt(100000, 999999));

        // 记录日志
        log.info("生成验证码，手机号：{}，验证码：{}", mobilePhone, code);

        // 将验证码放入Redis 设置失效时间为5分钟
        redisCache.setCacheObject(CacheConstants.SMS_CODE_PREFIX + mobilePhone, code, 5, TimeUnit.MINUTES);
        return AjaxResult.success("生成成功", code);
    }
}